<?php
require_once("LSina.class.php");
require_once("LRenRen.class.php");
class LSync {
	
	static private $websArr = array('renren','sina','kaixin001','douban');
	
	static public function GetSocialNetworkWeigths($user_id){
		$weights = array();
		$total = 0;
		$sync = Table::Fetch('sync', $user_id);
		foreach(self::$websArr as $one){
			if($sync[$one] == 1){
				$tmp = Table::Fetch('sync_' . $one, $user_id);
				if($tmp){
					$weights[$one] = $tmp['weight'];
					$total += $tmp['weight'];
				}
			}
		}
		$weights['total'] = $total;
		return $weights;
	}
	
	static public function MakeAuthUrl($web, $callbackUrl){
		switch ($web){
			case "sina":
				return LSina::getAuthUrl($callbackUrl);
			case "renren":
				return LRenRen::getAuthUrl($callbackUrl);
			default:
				return null;
		}
	}

    static public function Connect(&$user_id, $web, $email_oauthToken=null, $password_oauthTokenSecret=null) 
	{
		// 获取同步信息
		$ret = false;
		switch ($web){
			case "renren":
				$ret = LRenren::connect($user_id, $email_oauthToken, $password_oauthTokenSecret);
				break;
			case "sina":				
				$ret = LSina::connect($user_id, $email_oauthToken, $password_oauthTokenSecret);
				break;
			default:
				break;
		}
		if($ret){
			// 设定同步标识
			$sql  = "";
		}
	}
	
	/**
	 * 第三方平台登录，登录成功，写session['user'] = array("user_id","name")
	 * @return boolean 
	 * @author nevor
	 */
	static public function Login(&$user_id, $web, $oauth_token=null, $oauth_token_secret=null){
		switch ($web){
			case "sina":				
				$ret = LSina::connect($user_id, $oauth_token, $oauth_token_secret);
				if($ret){
					if(!isset($_SESSION['user'])){
						$_SESSION['user'] = array("user_id"=>$ret["user_id"], "name"=>$ret["name"]);
					}
					return true;
				}
				break;
			case "renren":
				$code = $_REQUEST['code'];
				$ret = LRenren::connect($user_id, $code);
				if($ret){
					if(!isset($_SESSION['user'])){
						$_SESSION['user'] = array("user_id"=>$ret["user_id"], "name"=>$ret["name"]);
					}
					return true;
				}
				break;
			default:
				break;
		}
		return false;
	}
	
	static public function Disconnect($user_id, $web){
		$table = new Table('sync', array(
			'id' => $user_id,
			$web => 0,
		));
		$table->update(array('id', $web));
		
		// 删除对应同步信息表中的记录
		Table::Delete('sync_' . $web, $user_id);
	}	

    static public function Publish($user_id, $user_network_weights, $msg, $longURL, $shortURL)
	{
		// 发布消息，并更新权重信息
		$result = array();
		foreach($user_network_weights as $index=>$one){
			switch ($index){
				case "renren":
					$result[$index] = LRenren::publish($user_id, $shortURL, $msg);
					break;
				case "sina":
					$result[$index] = LSina::publish($user_id, $msg." ".$longURL);
					break;
				case "total":
					break;
				default:
					break;
			}
		}
		return $result;
	}
}